"use client";

import { useSessionContext } from "@supabase/auth-helpers-react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { AiFillHeart, AiOutlineHeart } from "react-icons/ai";
import toast from "react-hot-toast";

import useAuthModal from "@/hooks/useAuthModal";
import { useUser } from "@/hooks/useUser";

interface LikeButtonProps {
  songId: string;
}

const LikeButton: React.FC<LikeButtonProps> = ({ songId }) => {
  const router = useRouter();
  const { supabaseClient } = useSessionContext();
  const authModal = useAuthModal();
  const { user } = useUser();
  const [ isLiked, setIsLiked ] = useState(false);

  //用户添加喜欢音乐的操作
  useEffect(() => {
    if(!user?.id) return;
    
    const fetchData = async() => {
      //supabase数据库查询操作
      const { data, error } = await supabaseClient
        .from('liked_songs')
        .select('*')
        .eq('user_id', user.id)
        .eq('song_id', songId)
        .single();

      if(!error && data) setIsLiked(true);
    }

    fetchData();

  }, [songId, supabaseClient, user?.id]);

  const Icon = isLiked ? AiFillHeart : AiOutlineHeart;

  const handleLike = async() => {
    if(!user) authModal.onOpen();
    //点击已经喜欢的按钮则删除数据库中的喜欢歌曲
    if(isLiked){
      const { error } = await supabaseClient
        .from('liked_songs')
        .delete()
        .eq('user_id', user!.id)
        .eq('song_id', songId);

      if(error){
        toast.error(error.message);
      }else{
        setIsLiked(false);
        toast.success('从喜欢歌曲中成功移除该歌曲！');
      }
    }else{
      //否则在数据库中新增喜欢的歌曲
      const { error } = await supabaseClient
        .from('liked_songs')
        .insert({ song_id: songId, user_id: user!.id });

      if(error){
        toast.error(error.message);
      }else{
        setIsLiked(true);
        toast.success('成功添加至喜欢歌曲！');
      }
    }

    router.refresh();
  }

  return (
    <button
      onClick={handleLike}
      className="
        hover:opacity-75
        transition
      ">
      <Icon
        color={isLiked ? '#22c55e' : 'white'}
        size={25}
      />
    </button>
  )
}

export default LikeButton;